package utils

type timerCommand struct {
	freqSeconds float64
	cmd         func()
	accumulate  float64
}

func (c *timerCommand) Update(dt float64) {
	c.accumulate += dt
	if c.accumulate < c.freqSeconds {
		return
	}
	c.accumulate = 0
	c.cmd()

}

var commonTimer *Timer

func CommonTimer() *Timer {
	if commonTimer == nil {
		commonTimer = &Timer{}
	}
	return commonTimer
}

type Timer struct {
	commands []*timerCommand
}

func (t *Timer) AddCommand(freqMilliseconds int, cmd func()) {
	t.commands = append(t.commands, &timerCommand{freqSeconds: float64(freqMilliseconds) / 1e3, cmd: cmd, accumulate: 0})
}

func (t *Timer) Update(dt float64) {
	for _, tc := range t.commands {
		tc.Update(dt)
	}
}

func (t *Timer) Clear() {
	t.commands = []*timerCommand{}
}
